package com.wawei.seeds.me;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import com.wawei.seeds.R;
import com.wawei.seeds.utils.PrefUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by itachi on 15/7/31.
 */
public class MeSettingsCheckUpdateActivity extends Activity {
    @InjectView(R.id.moreBkg)View moreBkg;
    @InjectView(R.id.walnut_update_app)View submit;
    private DownloadManager downloadManager;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_update);

        ButterKnife.inject(this);

        url = getIntent().getStringExtra("url");

        if (url == null || url.length() < 1) {
            finish();
            return;
        }

        downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);

        moreBkg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.moreBkg) {
                    MeSettingsCheckUpdateActivity.this.finish();
                }
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                update();
            }
        });
    }

    private void update() {
        Uri resource = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(resource);
        // 手机网络和wifi都下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //设置下载后文件存放的位置
        request.setDestinationInExternalPublicDir("/download/", "walnut.apk");
        // request.setDestinationInExternalFilesDir(this, null, "walnut.apk");
        //将下载请求放入队列
        long reference = downloadManager.enqueue(request);
        PrefUtils.markReference(MeSettingsCheckUpdateActivity.this, reference);
        MeSettingsCheckUpdateActivity.this.finish();
    }
}
